"""
Case Type   : openGauss 支持忽略PLSQL间的依赖进行创建
Case Name   : 存储过程的参数类型使用包中定义的类型
Create At   : 2023.11.23
Owner       : zhanghuan96
Description :
    1. 使用gs_guc reload方式设置参数为plpgsql_dependency
    2. 创建自定义类型
    3. 创建包，包中定义数组类型和表类型
    4. 创建存储过程,参数类型使用包中定义的数组类型
    5. 查询系统表
    6. 创建存储过程，存储过程的参数类型使用不存在包的类型
    7. 查询系统表
    8.清理环境
Expect      :
    1. 成功
    2. 成功
    3. 成功
    4. 成功
    5. valid字段返回t
    6. 弹出告警，创建成功
    7. valid字段返回f
    8. 成功
History     :
"""
import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node


class PlpgsqlDependency(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.common = Common()
        self.constant = Constant()
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.pri_node = Node('PrimaryDbUser')
        self.type_name = "type_guc0045"
        self.pkg_name = "pkg_guc0045"
        self.proc_name = "proc_guc0045"
        self.default_value = self.common.show_param('behavior_compat_options')

    def test_guc(self):
        text = '--step1:使用gs_guc reload方式设置参数为plpgsql_dependency;' \
               'expect:成功--'
        self.log.info(text)
        mod_msg = self.pri_sh.execute_gsguc('reload',
                                            self.constant.GSGUC_SUCCESS_MSG,
                                            "behavior_compat_options "
                                            "='plpgsql_dependency'")
        self.log.info(mod_msg)
        self.assertTrue(mod_msg)
        sql_cmd = "show behavior_compat_options;"
        self.log.info(sql_cmd)
        sql_res = self.pri_sh.execut_db_sql(sql_cmd)
        self.log.info(sql_res)
        self.assertEqual('plpgsql_dependency',
                         sql_res.splitlines()[-2].strip(),
                         '查询失败')

        text = '--step2:创建自定义类型;expect:成功--'
        self.log.info(text)
        sql_cmd = f'''drop type if exists {self.type_name};
        create type {self.type_name} as(a int, b int);'''
        sql_res = self.pri_sh.execut_db_sql(sql_cmd)
        self.log.info(sql_res)
        self.assertIn('CREATE TYPE', sql_res, '查询失败')

        text = '--step3:创建包，包中定义数组类型和表类型;expect:成功--'
        self.log.info(text)
        sql_cmd = f'''drop package if exists {self.pkg_name};
        create or replace package {self.pkg_name}
        is
            type arr_type0045 is varray(888) of {self.type_name};
            type t_type0045 is table of {self.type_name} index by \
            binary_integer;
            procedure proc_0045;
        end {self.pkg_name};
        '''
        self.log.info(sql_cmd)
        sql_res = self.pri_sh.execut_db_sql(sql_cmd)
        self.log.info(sql_res)
        self.assertIn('CREATE PACKAGE', sql_res, '查询失败')

        text = '--step4:创建存储过程,参数类型使用包中定义的数组类型;expect:成功--'
        self.log.info(text)
        sql_cmd = f'''drop procedure if exists {self.proc_name};
        create or replace procedure {self.proc_name}\
        (v_1 {self.pkg_name}.arr_type0045) as
        begin
            null;
        end;
        '''
        self.log.info(sql_cmd)
        sql_res = self.pri_sh.execut_db_sql(sql_cmd)
        self.log.info(sql_res)
        self.assertIn('CREATE PROCEDURE', sql_res, '查询失败')

        text = '--step5:查询系统表;expect:valid字段返回t--'
        self.log.info(text)
        sql_cmd = f'''select valid from pg_object where object_type='P' \
        and object_oid in (select Oid from pg_proc where propackageid = 0 \
        and proname='{self.proc_name}' and pronamespace = \
        (select Oid from pg_namespace where nspname = 'public'));'''
        self.log.info(sql_cmd)
        sql_res = self.pri_sh.execut_db_sql(sql_cmd)
        self.log.info(sql_res)
        self.assertIn('valid \n-------\n t\n(1 row)', sql_res, '查询失败')

        self.log.info('依赖对象的系统表成功')
        sql_cmd = f'''select a.schemaname as sn, a.packagename as pn, \
        a.objectname as on, a.refobjpos as refpos,
         b.schemaname as refsn, b.packagename as refpn, b.name as refon, \
         b.type as refot, b.objnode as refast
         from gs_dependencies as a right join gs_dependencies_obj as \
         b on b.oid = a.refobjoid where (a.schemaname='public' and \
         a.objectname = \
         '{self.proc_name}(public.{self.pkg_name}.arr_type0045)')
         or (b.schemaname='public' and \
         b.name = '{self.proc_name}(public.{self.pkg_name}.arr_type0045)')
         order by a.schemaname, a.objectname, a.refobjpos, b.type, b.name;
        '''
        self.log.info(sql_cmd)
        sql_res = self.pri_sh.execut_db_sql(sql_cmd)
        self.log.info(sql_res)
        self.assertIn('(2 rows)', sql_res, '查询失败')

        text = '--step6:创建存储过程，存储过程的参数类型使用不存在包的类型;' \
               'expect:弹出告警，创建成功--'
        self.log.info(text)
        sql_cmd = f'''drop type if exists arr1 cascade;
        drop package if exists {self.pkg_name}_01;
        drop procedure if exists {self.proc_name}_01;
        create or replace procedure {self.proc_name}_01\
        (v_1 {self.pkg_name}_01.arr1) as
        begin
            null;
        end;
        '''
        self.log.info(sql_cmd)
        sql_res = self.pri_sh.execut_db_sql(sql_cmd)
        self.log.info(sql_res)
        self.assertIn('WARNING:  Type arr1 does not exist.', sql_res, '查询失败')
        self.assertIn('CREATE PROCEDURE', sql_res, '查询失败')

        text = '--step7:查询系统表;expect:valid字段返回f--'
        self.log.info(text)
        sql_cmd = f'''select valid from pg_object where object_type='P' \
        and object_oid in (select Oid from pg_proc where propackageid = 0 \
        and proname='{self.proc_name}_01' and pronamespace = \
        (select Oid from pg_namespace where nspname = 'public'));
        '''
        self.log.info(sql_cmd)
        sql_res = self.pri_sh.execut_db_sql(sql_cmd)
        self.log.info(sql_res)
        self.assertIn('valid \n-------\n f\n(1 row)', sql_res, '查询失败')

    def tearDown(self):
        text = '----step8:清理环境;expect:成功----'
        self.log.info(text)
        sql_cmd = f"drop package if exists {self.pkg_name};" \
                  f"drop type if exists {self.type_name} cascade;" \
                  f"drop procedure if exists {self.proc_name}_01;"
        self.log.info(sql_cmd)
        sql_res = self.pri_sh.execut_db_sql(sql_cmd)
        self.log.info(sql_res)
        mod_msg = self.pri_sh.execute_gsguc('reload',
                                            self.constant.GSGUC_SUCCESS_MSG,
                                            f"behavior_compat_options "
                                            f"='{self.default_value}'")
        self.log.info(mod_msg)
        self.assertTrue(mod_msg)
        self.assertIn('DROP PACKAGE', sql_res, '删除失败')
        self.assertIn('DROP TYPE', sql_res, '删除失败')
        self.assertIn('DROP PROCEDURE', sql_res, '删除失败')
        self.log.info(f"-----{os.path.basename(__file__)} end-----")
